package com.cxy;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class JSONFlattener {
    public static List<JSONObject> flatten(JSONObject json) {
        List<JSONObject> result = new ArrayList<>();
        flatten(json, null, result);
        return result;
    }

    private static void flatten(Object obj, String pre, List<JSONObject> result) {
        if (pre == null){
            pre = "";
        }else{
            pre += ".";
        }
        if (obj instanceof JSONArray) {
            JSONArray array = (JSONArray) obj;
            for (int i = 0; i < array.length(); i++) {
                flatten(array.get(i),pre + i ,result);
            }
        } else if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                if (value instanceof JSONArray || value instanceof JSONObject){
                    flatten(value,pre + key,result);
                }else{
                    HashMap<Object, Object> map = new HashMap<>();
                    map.put(pre + key,value);
                    result.add(new JSONObject(map));
                }
            }
        }
    }

    public static void main(String[] args) {
        String s = """
                        {
                            "code":0,
                            "msg":"msg",
                            "data":{
                                "common":{
                                    "cok1":"cov1",
                                    "cok2":"ckv2"
                                },
                                "list1":[
                                    {"list1_k1":"list1_v1","list1_k2":"list1_v2"}
                                ],
                                "list2":[
                                    {"list2_k1":"list2_v1","list2_k2":"list2_v2"}
                                ]
                            }
                     
                        }        
                """;
        JSONObject json = new JSONObject(s);
        List<JSONObject> flattenedData = flatten(json);
        for (JSONObject obj : flattenedData) {
            System.out.println(obj);
        }
    }
}